package com.qianfeng.wuyang.himalaya.adapter.clsssifyadapter;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.qianfeng.wuyang.himalaya.R;
import com.qianfeng.wuyang.himalaya.bean.classifybean.Entity_Classify;
import com.qianfeng.wuyang.himalaya.bean.classifybean.Entity_classifyTop;
import com.qianfeng.wuyang.himalaya.callback.classifycallback.Classify_footpager_Service;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by ShenHao on 2016/12/5.
 */

public class Adapter_classify extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Callback<Entity_classifyTop>, ViewPager.OnPageChangeListener {
    private List<Entity_Classify> list_data;
    private Context context;
    private LayoutInflater inflater;
    private RecyclerView recyclerView;
    private GridLayoutManager manager;
    private ImageView []imageViews;
    ViewPager viewpager;
    private int ccurPosition;
    private Timer timer;


    public static final int HEAD_TYPE = 0;
    public static final int CONTENT_TYPE = 1;
    public static final int FOOT_TYPE = 2;

    public Adapter_classify(List<Entity_Classify> list_data, Context context) {
        this.list_data = list_data;
        this.context = context;
        inflater = LayoutInflater.from(context);
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == HEAD_TYPE) {
            View veiw = inflater.inflate(R.layout.fragment_classify_header, parent, false);
            return new HeadViewholder(veiw);
        } else if (viewType == CONTENT_TYPE) {
            View view = inflater.inflate(R.layout.fragment_classify_item, parent, false);

            return new ContentViewholder(view);
        } else {
            View view = inflater.inflate(R.layout.fragment_classify_foot, parent, false);
            viewpager= (ViewPager) view.findViewById(R.id.classify_viewpager_foot);
            return new FootViewholder(view);
        }
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (list_data.size()>0) {
        switch (getItemViewType(position)) {
            case HEAD_TYPE:
                HeadViewholder headViewholder = (HeadViewholder) holder;
                Picasso.with(context).load(list_data.get(0).getCoverPath()).into(headViewholder.imageView);
                break;
            case CONTENT_TYPE:
                ContentViewholder contentViewholder = (ContentViewholder) holder;
                Picasso.with(context).load(list_data.get(position).getCoverPath()).into(contentViewholder.imageView);
                contentViewholder.textView.setText(list_data.get(position).getTitle());

                break;
            case FOOT_TYPE:
                Classify_footpager_Service service=new Retrofit.Builder()
                        .baseUrl("http://adse.ximalaya.com/")
                        .addConverterFactory(GsonConverterFactory.create())
                        .build()
                        .create(Classify_footpager_Service.class);
                service.getPager("android","cata_index_banner","wifi",0,"4.3.98").enqueue(this);

                break;
        }
        }
    }
    @Override
    public void onAttachedToRecyclerView(final RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView = recyclerView;


        manager = new GridLayoutManager(context, 2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup(){
            @Override
            public int getSpanSize(int position) {
                if (position==0||position==getItemCount()-1) {
                    return 2;
                }
                return 1;
            }
        });
        RecyclerView.ItemDecoration decoration=new RecyclerView.ItemDecoration(){
            @Override
            public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
                super.onDrawOver(c, parent, state);
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position=recyclerView.getChildAdapterPosition(view);
                if ((position+1)%6==0){
                outRect.set(0,0,1,30);
                }else if(position%6==0&&position!=0){
                    outRect.set(1,0,0,30);
                }else if (position%2==0){
                    outRect.set(1,0,0,1);
                }else{
                    outRect.set(0,0,1,1);
                }
            }
        };
        this.recyclerView.setLayoutManager(manager);
        this.recyclerView.addItemDecoration(decoration);
    }

    @Override
    public int getItemCount() {
        return list_data.size() + 1;
    }


    @Override
    public int getItemViewType(int position) {
        if (position == 0) {
            return HEAD_TYPE;
        } else if (position == list_data.size()) {
            return FOOT_TYPE;
        } else {
            return CONTENT_TYPE;
        }
    }

    @Override
    public void onResponse(Call<Entity_classifyTop> call, Response<Entity_classifyTop> response) {
        String imageurls[]=new String[response.body().getData().size()+2];
        String adhtmls[]=new String[response.body().getData().size()+2];
        imageViews=new ImageView[response.body().getData().size()+2];
        for (int i = 0; i < response.body().getData().size(); i++) {
            ImageView image=new ImageView(context);
            imageViews[i+1]=image;
            imageurls[i+1]=response.body().getData().get(i).getCover();
            adhtmls[i+1]=response.body().getData().get(i).getLink();
        }
        imageViews[0]=new ImageView(context);
        imageViews[imageViews.length-1]=new ImageView(context);

        imageurls[0]=response.body().getData().get(response.body().getData().size()-1).getCover();
        imageurls[imageViews.length-1]=response.body().getData().get(0).getCover();

        adhtmls[0]=response.body().getData().get(response.body().getData().size()-1).getLink();
        adhtmls[imageViews.length-1]=response.body().getData().get(0).getLink();

        List<ImageView>list=new ArrayList<>();
        List<String>listhtmls=new ArrayList<>();
        for (int i = 0; i < imageViews.length; i++) {
            Picasso.with(context).load(imageurls[i]).into(imageViews[i]);
            list.add(imageViews[i]);
            listhtmls.add(adhtmls[i]);
        }
        Adapter_Classify_Footpager adapter=new Adapter_Classify_Footpager(list,listhtmls,context);
        viewpager.setAdapter(adapter);
        viewpager.setCurrentItem(1,false);
        viewpager.addOnPageChangeListener(this);
        startTimer();
    }
    private void startTimer() {
        timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message msg=Message.obtain();
                msg.what=MSG_WHAT;
                handler.sendEmptyMessage(msg.what);
            }
        }, 0, 5000);
    }
    public static final int MSG_WHAT=1;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_WHAT:
                    ccurPosition++;
                    viewpager.setCurrentItem(ccurPosition,true);
                break;
            }
        }
    };
    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (ccurPosition==0){
                    viewpager.setCurrentItem(imageViews.length-2,false);
                }else if (ccurPosition==imageViews.length-1){
                    viewpager.setCurrentItem(1,false);
                }
                if (timer==null){
                    ccurPosition--;
                    startTimer();
                }
                break;
            case ViewPager.SCROLL_STATE_DRAGGING:
                if (timer!=null){
                    timer.cancel();
                    timer=null;
                }
                break;
        }
    }

    @Override
    public void onFailure(Call<Entity_classifyTop> call, Throwable t) {

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
       ccurPosition=position;
    }

    public class ContentViewholder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;
        public ContentViewholder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.include_classify_image);
            textView = (TextView) itemView.findViewById(R.id.include_classify_text);
        }
    }

    public class HeadViewholder extends RecyclerView.ViewHolder {
        ImageView imageView;

        public HeadViewholder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.classify_image_head);
        }
    }

    public class FootViewholder extends RecyclerView.ViewHolder {

        public FootViewholder(View itemView) {
            super(itemView);

        }
    }


}
